package com.otaviolube.bibliotecas;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {
	
	static InputStream is = null;
	public JSONObject jObj = null;
	static String json = "";
	
	//Construtor da classe 
	public JSONParser(){
		jObj = new JSONObject();
	}	
	
	//Funcao que pega o codigo JSON atraves de uma requisicao web
	public JSONObject getJSONFromUrl(String url, List<NameValuePair> params){
		//Fazendo uma requisicao Http para trazer as inforacoes do JSON
		try{
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);
			httpPost.setEntity(new UrlEncodedFormEntity(params));
			
			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			is = httpEntity.getContent();
		}catch(UnsupportedEncodingException e){
			e.printStackTrace();
		}catch (ClientProtocolException e) {
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}
		
		//Agora vamos trabalhar com o que foi pego da requisicao Http
		try{
			BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while((line = reader.readLine()) != null){
				sb.append(line + "\n");
			}
			is.close();
			json = sb.toString();
			//Jogando o resultado no log para conferencia
			Log.e("JSON", json);
		}catch(Exception e){
			Log.e("BUFFER ERROR", "Erro ao converter resultado " + e.toString());
		}
		
		//Por fim tentamos fazer o parser da string da requisicao Http para um objeto JSON
		try{
			jObj = new JSONObject(json);
		}catch(JSONException e){
			Log.e("JSON PARSER", "Erro ao fazer o parser de " + e.toString());
		}
		
		//Retorna o objeto JSON
		return jObj;
	}

}
